Page({
    data: {
        pageNum: 1,
        dataList: [], // 咨询师列表数据
        pageTotal: 0,
        baseUrl: 'http://localhost:8080',
        counselorGradeId: null, // 接收的等级ID
        selectedDate: "",
        desc: "",
        userId: 0,
        loading: false // 加载状态
    },

    onLoad(options) {
        const app=getApp()
        const loginUserInfo = app.globalData.loginUserInfo
        if (!loginUserInfo || !loginUserInfo.id) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            wx.redirectTo({
                url: `/pages/login/login?url=/pages/consultBookingSelect/consultBookingSelect`
            });
            return;
        }

        // 2. 接收并处理参数（已能正确接收desc）
        const {
            counselorGradeId,
            selectedDate,
            desc
        } = options || {};
        let decodedDesc = '';
        if (desc) {
            decodedDesc = decodeURIComponent(desc); // 解码情况说明
        }

        // 处理默认日期
        const today = new Date().toISOString().split('T')[0];
        const validSelectedDate = selectedDate || today;

        this.setData({
            counselorGradeId: parseInt(counselorGradeId) || null,
            selectedDate: validSelectedDate,
            desc: decodedDesc, // 保存解码后的情况说明
            userId: loginUserInfo.id
        }, () => {
            this.getData(); // 加载列表数据
        });
    },

    // 获取咨询师列表数据
    getData() {
        this.setData({
            loading: true
        }); // 显示加载中
        wx.showLoading({
            title: '加载中...'
        });

        wx.request({
            url: 'http://localhost:8080/counselor/page?post=0',
            data: {
                channelId: 409,
                pageNum: this.data.pageNum,
                pageSize: 15,
                counselorGradeId: this.data.counselorGradeId
            },
            method: 'GET',
            success: (resp) => {
                if (resp.data && resp.data.code === 200) {
                    const totalPage = resp.data.data.pageTotal || 0;
                    let currentPageData = resp.data.data.list || [];

                    // 确保数据中包含id字段
                    currentPageData = currentPageData.map(item => {
                        // 如果后端返回的是counselorId而不是id，进行映射
                        if (!item.id && item.counselorId) {
                            item.id = item.counselorId;
                        }
                        
                        // 处理头像URL
                        if (item.headImageUrl && !item.headImageUrl.startsWith('http')) {
                            item.headImageUrl = this.data.baseUrl + item.headImageUrl;
                        }
                        return item;
                    });

                    this.setData({
                        dataList: this.data.dataList.concat(currentPageData),
                        pageTotal: totalPage
                    });
                } else {
                    wx.showToast({
                        title: '获取数据失败',
                        icon: 'none'
                    });
                }
            },
            fail: () => {
                wx.showToast({
                    title: '网络异常',
                    icon: 'none'
                });
            },
            complete: () => {
                this.setData({
                    loading: false
                });
                wx.hideLoading();
                wx.stopPullDownRefresh();
            }
        });
    },

    // 下拉刷新
    onPullDownRefresh() {
        this.setData({
            pageNum: 1,
            dataList: [],
            pageTotal: 0
        }, () => {
            this.getData();
        });
    },

    // 上拉加载下一页
    onReachBottom() {
        if (this.data.loading || this.data.pageNum >= this.data.pageTotal) {
            return; // 避免重复加载
        }
        this.setData({
            pageNum: this.data.pageNum + 1
        }, () => {
            this.getData();
        });
    },

    // 点击咨询师条目跳转详情页（继续传递desc参数）
    onConsultantTap(e) {
        const counselorId = e.currentTarget.dataset.counselorId;
        if (!counselorId || isNaN(counselorId)) {
            wx.showToast({
                title: '获取咨询师ID失败',
                icon: 'none'
            });
            return;
        }

        // 获取页面数据
        const {
            counselorGradeId,
            selectedDate,
            desc,
            userId
        } = this.data;

        // 编码特殊字符
        const encodedDesc = encodeURIComponent(desc || '');

        // 跳转至确认页（携带完整参数）
        wx.navigateTo({
            url: `/index/pages/consultSelect/consultSelect?counselorId=${counselorId}&counselorGradeId=${counselorGradeId}&selectedDate=${selectedDate}&desc=${encodedDesc}&userId=${userId}`,
            fail: (err) => {
                console.error('跳转失败：', err);
                wx.showToast({
                    title: '跳转失败，请重试',
                    icon: 'none'
                });
            }
        });
    }
});
